import type { Directive } from 'vue'
import { useAuthStore } from '@/stores/auth'
import type { RouteRecordRaw } from 'vue-router'

// 权限指令
export const permission: Directive = {
  mounted(el, binding) {
    const authStore = useAuthStore()
    const { value } = binding
    
    if (value) {
      const hasPermission = authStore.hasPermission(value)
      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    }
  },
  updated(el, binding) {
    const authStore = useAuthStore()
    const { value } = binding
    
    if (value) {
      const hasPermission = authStore.hasPermission(value)
      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    }
  }
}

// 角色指令
export const role: Directive = {
  mounted(el, binding) {
    const authStore = useAuthStore()
    const { value } = binding
    
    if (value) {
      const hasRole = authStore.user?.role === value
      if (!hasRole) {
        el.parentNode?.removeChild(el)
      }
    }
  },
  updated(el, binding) {
    const authStore = useAuthStore()
    const { value } = binding
    
    if (value) {
      const hasRole = authStore.user?.role === value
      if (!hasRole) {
        el.parentNode?.removeChild(el)
      }
    }
  }
}

/**
 * 检查用户是否有权限访问路由
 * @param role 用户的角色
 * @param route 需要检查的路由
 */
function hasPermission(role: string, route: RouteRecordRaw): boolean {
  if (route.meta && route.meta.roles) {
    // 如果路由定义了 roles，检查用户角色是否在其中
    return (route.meta.roles as string[]).includes(role)
  } else {
    // 如果路由没有定义 roles，则默认所有登录用户都有权限
    return true
  }
}

/**
 * 根据用户角色递归过滤异步路由
 * @param routes 异步路由数组
 * @param role 用户的角色
 * @returns 过滤后的路由数组
 */
export function filterAsyncRoutes(routes: RouteRecordRaw[], role: string): RouteRecordRaw[] {
  const res: RouteRecordRaw[] = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(role, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, role)
      }
      res.push(tmp)
    }
  })

  return res
} 